import fnmatch
import glob
import os


# 递归遍历/xx/xx.../modules及其子目录，找出*Mapper.java文件。用法如下：
#     for file_path in find_files(
#             "/Users/xx_work/workspace/xx/modules",
#             "*Mapper.java"):
#         print(file_path)
def find_files(directory, pattern):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if fnmatch.fnmatchcase(file, pattern):
                yield os.path.join(root, file)


# 递归遍历/xx/xx.../modules及其子目录，找出*Mapper.java文件。用法如下：
#     files = find_file_with_glob(
#         "/Users/xx_work/workspace/xx/modules/**/*Mapper.java")
def find_file_use_glob(directory):
    return glob.glob(directory, recursive=True)


'''
    ########################################### 以上为基础方法，以下为实操 ###########################################
'''


# 查询所有*Mapper.java文件，并找出在测试基类中未定义过的
def findMapper(url1, url2):
    # 查找所有*Mapper.java文件
    files1 = find_file_use_glob(url1)
    # 转换名称后塞入List中
    notExistsMapper = []
    for content in files1:
        notExistsMapper.append(os.path.splitext(os.path.basename(content))[0])
    # 在当前类中找出已经定义的Mapper文件，并从List中移除
    with open(url2, 'r') as file2:
        for line in file2:
            for mapper in notExistsMapper:
                if mapper in line:
                    notExistsMapper.remove(mapper)
    print(notExistsMapper)


if __name__ == '__main__':
    # 在url2的文件中查找不存在的*Mapper
    # url1 = "/Users/xx_work/workspace/xx/rpc/client/**/*Client.java"
    url1 = "/Users/xx_work/workspace/xx/modules/**/*Mapper.java"
    url2 = "/Users/xx_work/workspace/xx/BaseApplicationTest.java"
    findMapper(url1, url2)
